package com.yuhan.common.exception;

import com.yuhan.common.enums.CodeEnum;
import com.yuhan.common.exception.BusinessException;
import com.yuhan.common.exception.RRException;
import com.yuhan.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: yuhan-common
 * @description: 异常处理器，拦截异常并统一处理，返回json格式
 * @author: hejing
 * @create: 2019-08-29 09:57
 **/
@ControllerAdvice
public class RRExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = RRException.class)
    @ResponseBody
    public R handleRRException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    /***
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return R.error(CodeEnum.ERROR_1001);
    }

    /**
     * 处理所有业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public R handleBusinessException(BusinessException e) {
        logger.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    /**
     * 处理所有接口数据验证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return R.error(CodeEnum.ERROR_1006.getCode(),e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /***
     * 数据重复插入的问题
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return R.error(CodeEnum.ERROR_1009);
    }
}
